package com.ms.banner;

import com.ms.banner.holder.BannerViewHolder;
import com.ms.banner.listener.OnBannerClickListener;
import com.ms.banner.util.Utils;
import com.ms.banner.view.ArcShapeView;
import com.ms.banner.view.BannerViewPager;
import ohos.agp.components.*;
import ohos.agp.components.element.Element;
import ohos.agp.components.element.PixelMapElement;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.service.DisplayManager;
import ohos.app.Context;
import ohos.eventhandler.EventRunner;
import ohos.global.resource.NotExistException;
import ohos.global.resource.Resource;
import ohos.global.resource.ResourceManager;
import ohos.global.resource.WrongTypeException;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;
import ohos.multimodalinput.event.TouchEvent;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_PARENT;

/**
 * 轮播图自定义控件
 */
public class Banner extends StackLayout implements PageSlider.PageChangedListener {

    private int mIndicatorPadding = BannerConfig.PADDING_SIZE;
    private int mIndicatorMargin = BannerConfig.MARGIN_BOTTOM;
    private int mIndicatorWidth;
    private int mIndicatorHeight;
    private int indicatorSize;
    private Element bannerBackgroundImage;
    private int bannerStyle = BannerConfig.CIRCLE_INDICATOR;
    private int delayTime = BannerConfig.TIME;
    private boolean isAutoPlay = BannerConfig.IS_AUTO_PLAY;
    private boolean isLoop = BannerConfig.IS_LOOP;
    private boolean isStart = false;
    private boolean isPrepare = false;
    private int mIndicatorSelectedResId = ResourceTable.Media_gray_dot;
    private int mIndicatorUnselectedResId = ResourceTable.Media_white_dot;
    private Element mIndicatorSelectedDrawable;
    private Element mIndicatorUnselectedDrawable;
    private int titleHeight;
    private Element titleBackground;
    private Color titleTextColor;
    private int mArcHeight;
    private Color mArcStartColor, mArcEndColor;
    private int mArcDirection;
    private int titleTextSize;
    private int count = 0;
    private int currentItem = 0;
    private int gravity = -1;
    private int lastPosition;
    private List<String> titles;
    private List mDatas;
    private BannerViewHolder creator;
    private List<Component> imageViews;
    private List<Image> indicatorImages;
    private Context context;
    private BannerViewPager viewPager;
    private Text bannerTitle, numIndicatorInside, numIndicator;
    private DirectionalLayout indicator, indicatorInside, titleView;
    private Image bannerDefaultImage;
    private BannerPagerAdapter adapter;
    private PageSlider.PageChangedListener mOnPageChangeListener;
    private OnBannerClickListener listener;
    private int mPageLeftMargin;
    private int mPageRightMargin;
    private EventRunner runner = EventRunner.current();
    private WeakHandler handler = new WeakHandler(runner);

    public Banner(Context context) {
        this(context, null);
    }

    public Banner(Context context, AttrSet attrSet) {
        this(context, attrSet, null);
    }

    public Banner(Context context, AttrSet attrSet, String styleName) {
        super(context, attrSet, styleName);
        init(context,attrSet);
    }

    /**
     * 初始化控件
     * @param attrs AttrSet
     * @param context  Context
     */
    private void init(Context context,AttrSet attrs) {
        this.context = context;
        titles = new ArrayList<>();
        mDatas = new ArrayList<>();
        imageViews = new ArrayList<>();
        indicatorImages = new ArrayList<>();
        DisplayManager dm = DisplayManager.getInstance();
        indicatorSize = dm.getDefaultDisplay(context).get().getAttributes().width / (int) Utils.getInstance().dp2Px(context, 35);
        handleTypedArray(attrs);
        Component view = LayoutScatter.getInstance(context).parse(ResourceTable.Layout_banner, this, true);
        bannerDefaultImage = (Image) view.findComponentById(ResourceTable.Id_bannerDefaultImage);
        viewPager = (BannerViewPager) view.findComponentById(ResourceTable.Id_bannerViewPager);
        viewPager.setPadding(mPageLeftMargin, 0, mPageRightMargin, 0);
        titleView = (DirectionalLayout) view.findComponentById(ResourceTable.Id_titleView);
        indicator = (DirectionalLayout) view.findComponentById(ResourceTable.Id_circleIndicator);
        indicatorInside = (DirectionalLayout) view.findComponentById(ResourceTable.Id_indicatorInside);
        bannerTitle = (Text) view.findComponentById(ResourceTable.Id_bannerTitle);
        numIndicator = (Text) view.findComponentById(ResourceTable.Id_numIndicator);
        numIndicatorInside = (Text) view.findComponentById(ResourceTable.Id_numIndicatorInside);
        bannerDefaultImage.setImageElement(bannerBackgroundImage);
        ArcShapeView arcShapeView = (ArcShapeView) view.findComponentById(ResourceTable.Id_bannerArcView);
        if (mArcHeight <= 0) {
            arcShapeView.setVisibility(HIDE);
        } else {
            arcShapeView.setVisibility(VISIBLE);
            arcShapeView.setArcHeight((int) Utils.getInstance().dp2Px(context,mArcHeight));
            arcShapeView.setBackground(mArcStartColor, mArcEndColor);
            arcShapeView.setDirection(mArcDirection);
            arcShapeView.invalidate();
        }
        DependentLayout.LayoutConfig indicatorParam = new DependentLayout.LayoutConfig(LayoutConfig.MATCH_PARENT,
                LayoutConfig.MATCH_CONTENT);
        indicatorParam.setMarginBottom((int) Utils.getInstance().dp2Px(context, mIndicatorMargin));
        indicator.setLayoutConfig(indicatorParam);
    }

    /**
     * 自定义属性
     * @param attrs
     */
    private void handleTypedArray(AttrSet attrs) {
        if (attrs == null) {
            return;
        }
        mIndicatorWidth = Utils.getInstance().getAttrIntValue(attrs, "indicator_width",
                (int) Utils.getInstance().dp2Px(context, indicatorSize));
        mIndicatorHeight = Utils.getInstance().getAttrIntValue(attrs, "indicator_height",
                (int) Utils.getInstance().dp2Px(context, indicatorSize));
        mIndicatorPadding = Utils.getInstance().getAttrIntValue(attrs, "indicator_padding",
                (int) Utils.getInstance().dp2Px(context, BannerConfig.PADDING_SIZE));
        mIndicatorMargin = Utils.getInstance().getAttrIntValue(attrs, "indicator_margin",
                (int) Utils.getInstance().dp2Px(context, BannerConfig.MARGIN_BOTTOM));
        mIndicatorSelectedResId = Utils.getInstance().getAttrIntValue(attrs, "indicator_drawable_selected",
                ResourceTable.Media_gray_dot);
        mIndicatorUnselectedResId = Utils.getInstance().getAttrIntValue(attrs, "indicator_drawable_unselected",
                ResourceTable.Media_white_dot);

        delayTime = Utils.getInstance().getAttrIntValue(attrs, "delay_time", BannerConfig.TIME);
        isAutoPlay = Utils.getInstance().getAttrBoolValue(attrs, "is_auto_play", BannerConfig.IS_AUTO_PLAY);
        isLoop = Utils.getInstance().getAttrBoolValue(attrs, "is_loop", BannerConfig.IS_LOOP);
        titleBackground = Utils.getInstance().getAttrElementValue(attrs, "title_background",
                new ShapeElement(getContext(), BannerConfig.TITLE_BACKGROUND));
        titleHeight = Utils.getInstance().getAttrIntValue(attrs, "title_height",
                (int) Utils.getInstance().dp2Px(context, BannerConfig.TITLE_HEIGHT));
        titleTextColor = Utils.getInstance().getAttrColorValue(attrs, "title_textcolor",
                new Color(BannerConfig.TITLE_TEXT_COLOR));
        titleTextSize = Utils.getInstance().getAttrIntValue(attrs, "title_textsize",
                (int) Utils.getInstance().dp2Px(context, BannerConfig.TITLE_TEXT_SIZE));

        mArcHeight = Utils.getInstance().getAttrIntValue(attrs, "arc_height",
                (int) Utils.getInstance().dp2Px(context, BannerConfig.ARC_HEIGHT));
        mArcStartColor = Utils.getInstance().getAttrColorValue(attrs, "arc_start_color",
                new Color(ResourceTable.Color_arc_start_color));
        mArcEndColor = Utils.getInstance().getAttrColorValue(attrs, "arc_end_color",
                new Color(ResourceTable.Color_arc_end_color));
        mArcDirection = Utils.getInstance().getAttrIntValue(attrs, "arc_direction",
                (int) Utils.getInstance().dp2Px(context, BannerConfig.ARC_DIRECTION));

        mPageLeftMargin = Utils.getInstance().getAttrIntValue(attrs, "page_left_margin",
                (int) Utils.getInstance().dp2Px(context, BannerConfig.PAGE_MARGIN));
        mPageRightMargin = Utils.getInstance().getAttrIntValue(attrs, "page_right_margin",
                (int) Utils.getInstance().dp2Px(context, BannerConfig.PAGE_MARGIN));
        try {
            bannerBackgroundImage = Utils.getInstance().getAttrElementValue(attrs, "banner_default_image",
                    new PixelMapElement(Utils.getInstance().getPixelMapFromMedia(getContext(), BannerConfig.DEFAULT_IMAGE)));
        } catch (NotExistException e) {
            e.printStackTrace();
        } catch (WrongTypeException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 设置自动播放
     * @param isAutoPlay isAutoPlay
     * @return Banner
     */
    public Banner setAutoPlay(boolean isAutoPlay) {
        this.isAutoPlay = isAutoPlay;
        return this;
    }

    /**
     * 设置是否循环
     * @param isLoop isLoop
     * @return Banner
     */
    public Banner setLoop(boolean isLoop) {
        this.isLoop = isLoop;
        this.viewPager.setCircularModeEnabled(isLoop);
        return this;
    }

    /**
     * 设置间隔轮播时间
     * @param delayTime  轮播时间
     * @return  Banner
     */
    public Banner setDelayTime(int delayTime) {
        this.delayTime = delayTime;
        return this;
    }

    /**
     * 设置指示器位置
     * @param type 位置
     * @return Banner
     */
    public Banner setIndicatorGravity(int type) {
        switch (type) {
            case BannerConfig.LEFT:
                this.gravity = LayoutAlignment.LEFT | LayoutAlignment.VERTICAL_CENTER;
                break;
            case BannerConfig.CENTER:
                this.gravity = LayoutAlignment.CENTER;
                break;
            case BannerConfig.RIGHT:
                this.gravity = LayoutAlignment.RIGHT | LayoutAlignment.VERTICAL_CENTER;
                break;
            default:
                break;
        }
        return this;
    }

    /**
     * 设置页面切换动画
     * @param transformer 动画
     * @return Banner
     */
    public Banner setBannerAnimation(Class<? extends BannerViewPager.PageTransformer> transformer) {
        try {
            viewPager.setPageTransformer(transformer.newInstance());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return this;
    }

    /**
     * 设置轮播图的标题
     * @param titles 标题
     * @return Banner
     */
    public Banner setBannerTitles(List<String> titles) {
        this.titles = titles;
        return this;
    }

    /**
     * 设置轮播图的样式
     * @param bannerStyle 样式
     * @return Banner
     */
    public Banner setBannerStyle(int bannerStyle) {
        this.bannerStyle = bannerStyle;
        return this;
    }

    /**
     * 设置轮播图的当前页面
     * @param page 页面
     * @return Banner
     */
    public Banner setCurrentPage(int page) {
        currentItem = page;
        return this;
    }

    /**
     * 设置轮播图页面
     * @param datas datas
     * @param creator BannerViewHolder
     * @return Banner
     */
    public Banner setPages(List<?> datas, BannerViewHolder creator) {
        this.mDatas.clear();
        this.imageViews.clear();
        this.mDatas.addAll(datas);
        this.creator = creator;
        this.count = datas.size();
        return this;
    }

    public PageSlider getSlider() {
        return viewPager;
    }

    /**
     * 更新轮播图页面和标题
     * @param imageUrls 轮播图
     * @param titles 标题
     */
    public void update(List<?> imageUrls, List<String> titles) {
        if (imageUrls == null || titles == null || imageUrls.size() != titles.size()) {
            update(null);
            return;
        }
        this.titles.clear();
        this.titles.addAll(titles);
        update(imageUrls);
    }
    public void reset(){
        this.mIndicatorSelectedDrawable=null;
        this.mIndicatorUnselectedDrawable=null;
        this.mIndicatorSelectedResId = 0;
        this.mIndicatorUnselectedResId = 0;
    }
    /**
     * 更新轮播图数据
     * @param imageUrls 轮播图数据
     */
    public void update(List<?> imageUrls) {
        if (imageUrls == null) {
            imageUrls = new ArrayList<>();
        }
        this.mDatas.clear();
        this.indicatorImages.clear();
        if (imageUrls.size() == 0) {
            bannerDefaultImage.setVisibility(VISIBLE);
            this.count = 0;
            if (adapter != null) {
                adapter.notifyDataChanged();
            }
        } else {
            this.mDatas.addAll(imageUrls);
            this.count = this.mDatas.size();
            start();
        }
    }

    /**
     * 更新轮播图样式
     * @param bannerStyle 样式
     */
    public void updateBannerStyle(int bannerStyle) {
        indicator.setVisibility(HIDE);
        numIndicator.setVisibility(HIDE);
        numIndicatorInside.setVisibility(HIDE);
        indicatorInside.setVisibility(HIDE);
        bannerTitle.setVisibility(HIDE);
        titleView.setVisibility(HIDE);
        this.bannerStyle = bannerStyle;
        lastPosition = 0;
        currentItem = 0;
        start();
    }

    /**
     * 开始轮播
     * @return Banner
     */
    public Banner start() {
        if (count > 0) {
            setStyleUI();
            setIndicator();
            setData();
        } else {
            bannerDefaultImage.setVisibility(VISIBLE);
        }
        return this;
    }

    /**
     * 设置指示器图片
     * @param select select
     * @param unSelect unSelect
     * @return Banner
     */
    public Banner setIndicatorRes(int select, int unSelect) {
        if (select < 0)
            throw new RuntimeException("[Banner] --> The select res is not exist");
        if (unSelect < 0)
            throw new RuntimeException("[Banner] --> The unSelect res is not exist");

        mIndicatorSelectedResId = select;
        mIndicatorUnselectedResId = unSelect;
        return this;
    }

    /**
     * 设置指示器图片
     * @param select select
     * @param unSelect unSelect
     * @return Banner
     */
    public Banner setIndicatorRes(Element select, Element unSelect) {
        if (select == null || unSelect == null)
            throw new RuntimeException("[Banner] --> The Drawable res is null");

        mIndicatorSelectedDrawable = select;
        mIndicatorUnselectedDrawable = unSelect;
        return this;
    }

    /**
     * 设置指示器样式
     */
    private void setStyleUI() {
        int visibility = count > 1 ? VISIBLE : HIDE;
        switch (bannerStyle) {
            case BannerConfig.CIRCLE_INDICATOR:
            case BannerConfig.CUSTOM_INDICATOR:
                indicator.setVisibility(visibility);
                break;
            case BannerConfig.NUM_INDICATOR:
                numIndicator.setVisibility(visibility);
                break;
            case BannerConfig.NUM_INDICATOR_TITLE:
                numIndicatorInside.setVisibility(visibility);
                setTitleStyleUI();
                break;
            case BannerConfig.CIRCLE_INDICATOR_TITLE:
                indicator.setVisibility(visibility);
                setTitleStyleUI();
                break;
            case BannerConfig.CIRCLE_INDICATOR_TITLE_INSIDE:
                indicatorInside.setVisibility(visibility);
                setTitleStyleUI();
                break;
            default:
                break;
        }
    }

    /**
     * 设置标题样式
     */
    private void setTitleStyleUI() {
        if (titles.size() != mDatas.size()) {
            throw new RuntimeException("[Banner] --> The number of titles and images is different");
        }
        if (titleBackground != null) {
            titleView.setBackground(titleBackground);
        }
        if (titleHeight != -1) {
            DependentLayout.LayoutConfig layoutConfig = new DependentLayout.LayoutConfig(DependentLayout.LayoutConfig.MATCH_PARENT, titleHeight);
            layoutConfig.addRule(DependentLayout.LayoutConfig.BELOW, ResourceTable.Id_circleIndicator);
            titleView.setLayoutConfig(layoutConfig);
        }
        if (titleTextColor != null) {
            bannerTitle.setTextColor(titleTextColor);
        }
        if (titleTextSize != -1) {
            bannerTitle.setTextSize(titleTextSize);
        }
        if (titles.size() > 0) {
            bannerTitle.setText(titles.get(0));
            bannerTitle.setVisibility(VISIBLE);
            titleView.setVisibility(VISIBLE);
        }
    }

    /**
     * 设置指示器
     */
    private void setIndicator() {
        bannerDefaultImage.setVisibility(HIDE);

        if (bannerStyle == BannerConfig.CIRCLE_INDICATOR ||
                bannerStyle == BannerConfig.CIRCLE_INDICATOR_TITLE ||
                bannerStyle == BannerConfig.CIRCLE_INDICATOR_TITLE_INSIDE ||
                bannerStyle == BannerConfig.CUSTOM_INDICATOR) {
            createIndicator();
        } else if (bannerStyle == BannerConfig.NUM_INDICATOR_TITLE) {
            numIndicatorInside.setText("1/" + count);
        } else if (bannerStyle == BannerConfig.NUM_INDICATOR) {
            numIndicator.setText("1/" + count);
        }
    }

    /**
     * 创建指示器
     */
    private void createIndicator() {
        indicatorImages.clear();
        indicator.removeAllComponents();
        indicatorInside.removeAllComponents();
        for (int i = 0; i < count; i++) {
            Image imageView = new Image(context);
            imageView.setScaleMode(Image.ScaleMode.CLIP_CENTER);
            DirectionalLayout.LayoutConfig params = new DirectionalLayout.LayoutConfig(mIndicatorWidth, mIndicatorHeight);
            params.setMarginLeft(mIndicatorPadding);
            params.setMarginRight(mIndicatorPadding);
            indicator.setAlignment(LayoutAlignment.CENTER);
            if (i == 0) {
                if (mIndicatorSelectedDrawable != null) {
                    imageView.setImageElement(mIndicatorSelectedDrawable);
                } else {
                    if (mIndicatorSelectedResId!=0) {
                        imageView.setImageAndDecodeBounds(mIndicatorSelectedResId);
                    }else {
                        imageView.setImageAndDecodeBounds(ResourceTable.Media_gray_dot);
                    }
                }
            } else {
                if (mIndicatorUnselectedDrawable != null) {
                    imageView.setImageElement(mIndicatorUnselectedDrawable);
                } else {
                    if (mIndicatorUnselectedResId!=0){
                        imageView.setImageAndDecodeBounds(mIndicatorUnselectedResId);
                    }else {
                        imageView.setImageAndDecodeBounds(ResourceTable.Media_white_dot);
                    }
                }
            }
            indicatorImages.add(imageView);
            if (bannerStyle == BannerConfig.CIRCLE_INDICATOR ||
                    bannerStyle == BannerConfig.CIRCLE_INDICATOR_TITLE) {
                indicator.addComponent(imageView, params);
            } else if (bannerStyle == BannerConfig.CIRCLE_INDICATOR_TITLE_INSIDE) {
                indicatorInside.addComponent(imageView, params);
            } else if (bannerStyle == BannerConfig.CUSTOM_INDICATOR) {
                indicator.addComponent(imageView, params);
            }
        }
        if (gravity != -1) {
            indicator.setAlignment(gravity);
        }
    }

    /**
     * 设置轮播图
     * @param imagesUrl
     * @return  List<Component>
     * @throws NotExistException
     * @throws WrongTypeException
     * @throws IOException
     */
    private List<Component> setImageList(List<?> imagesUrl) throws NotExistException, WrongTypeException, IOException {
        if (imagesUrl == null || imagesUrl.size() <= 0) {
            bannerDefaultImage.setVisibility(VISIBLE);
            return null;
        }
        bannerDefaultImage.setVisibility(HIDE);
        for (int i = 0; i < imagesUrl.size(); i++) {
            Object url = imagesUrl.get(i);
            Image image1 = new Image(context);
            image1.setScaleMode(Image.ScaleMode.STRETCH);
            image1.setLayoutConfig(new ComponentContainer.LayoutConfig(MATCH_PARENT, MATCH_PARENT));
            if (url instanceof String) {
                Utils.getInstance().setBitmap(context, image1, (String) url);
            } else {
                ImageSource.SourceOptions options = new ImageSource.SourceOptions();
                options.formatHint = "image/jpg";
                ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
                ResourceManager manager = context.getResourceManager();
                String path = manager.getMediaPath((Integer) url);
                Resource r1 = manager.getRawFileEntry(path).openRawFile();
                ImageSource source = ImageSource.create(r1, options);
                PixelMap p1 = source.createPixelmap(decodingOptions);
                image1.setPixelMap(p1);
            }
            imageViews.add(image1);
        }
        return imageViews;
    }

    /**
     * 绑定数据源
     */
    private void setData() {
        viewPager.setPages(imageViews);
        if (adapter == null) {
            adapter = new BannerPagerAdapter();
            viewPager.setCircularModeEnabled(isLoop);
            viewPager.addPageChangedListener(this);
            viewPager.setProvider(adapter);
        } else {
            adapter.notifyDataChanged();
        }
        viewPager.setFocusable(1);
        if (gravity != -1) {
            indicator.setAlignment(gravity);
        }
        viewPager.setCurrentPage(currentItem);
        this.setTouchEventListener(new TouchEventListener() {
            @Override
            public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
                switch (touchEvent.getAction()) {
                    case TouchEvent.PRIMARY_POINT_UP:
                    case TouchEvent.CANCEL:
                    case TouchEvent.TOUCH_PANEL:
                        startAutoPlay();
                        break;
                    case TouchEvent.PRIMARY_POINT_DOWN:
                        stopAutoPlay();
                        break;
                    default:
                        break;
                }
                return true;
            }
        });
        startAutoPlay();
    }

    /**
     * 开始轮播
     */
    public void startAutoPlay() {
        handler.removeCallbacks(task);
        handler.postDelayed(task, delayTime);
    }

    /**
     * 停止轮播
     */
    public void stopAutoPlay() {
        handler.removeCallbacks(task);
    }

    /**
     * 轮播任务线程
     */
    private final Runnable task = new Runnable() {
        @Override
        public void run() {
            if (count > 1 && isAutoPlay) {
                currentItem++;
                if (currentItem >= count) {
                    currentItem = 0;
                }
                viewPager.setCurrentPage(currentItem, true);
                handler.postDelayed(task, delayTime);
            }
        }
    };

    /**
     * PageSlider适配器
     */
    private class BannerPagerAdapter extends PageSliderProvider {

        @Override
        public int getCount() {
            return mDatas.size();
        }

        @Override
        public Object createPageInContainer(ComponentContainer container, int position) {
            Component component = null;
            if (creator == null) {
                try {
                    imageViews = setImageList(mDatas);
                    component = imageViews.get(position);
                } catch (NotExistException e) {
                    e.printStackTrace();
                } catch (WrongTypeException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }else {
                try {
                    component = creator.createView(container.getContext(), position, mDatas.get(position));
                } catch (NotExistException e) {
                    e.printStackTrace();
                } catch (WrongTypeException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            container.addComponent(component);

            if (listener != null) {
                component.setClickedListener(new ClickedListener() {
                    @Override
                    public void onClick(Component component) {
                        listener.onBannerClick(mDatas, position);
                    }
                });
            }
            return component;
        }

        @Override
        public void destroyPageFromContainer(ComponentContainer container, int i, Object object) {
            if(container == null || object == null) return;
            container.removeComponent((Component) object);
        }

        @Override
        public boolean isPageMatchToObject(Component component, Object o) {
            return component == o;
        }
    }

    @Override
    public void onPageSlideStateChanged(int state) {
        if (mOnPageChangeListener != null) {
            mOnPageChangeListener.onPageSlideStateChanged(state);
        }
    }

    @Override
    public void onPageSliding(int position, float positionOffset, int positionOffsetPixels) {
        if (mOnPageChangeListener != null) {
            mOnPageChangeListener.onPageSliding(position, positionOffset, positionOffsetPixels);
        }
    }
    @Override
    public void onPageChosen(int position) {
        currentItem = position;
        if (mOnPageChangeListener != null) {
            mOnPageChangeListener.onPageChosen(position);
        }
        if (bannerStyle == BannerConfig.CIRCLE_INDICATOR ||
                bannerStyle == BannerConfig.CIRCLE_INDICATOR_TITLE ||
                bannerStyle == BannerConfig.CIRCLE_INDICATOR_TITLE_INSIDE ||
                bannerStyle == BannerConfig.CUSTOM_INDICATOR) {
            if (mIndicatorSelectedDrawable != null && mIndicatorUnselectedDrawable != null) {
                indicatorImages.get(lastPosition).setImageElement(mIndicatorUnselectedDrawable);
                indicatorImages.get(position).setImageElement(mIndicatorSelectedDrawable);
            } else {
                if (mIndicatorUnselectedResId!=0) {
                    indicatorImages.get(lastPosition).setImageAndDecodeBounds(mIndicatorUnselectedResId);
                }else {
                    indicatorImages.get(lastPosition).setImageAndDecodeBounds(ResourceTable.Media_white_dot);
                }
                if (mIndicatorSelectedResId!=0) {
                    indicatorImages.get(position).setImageAndDecodeBounds(mIndicatorSelectedResId);
                }else {
                    indicatorImages.get(position).setImageAndDecodeBounds(ResourceTable.Media_gray_dot);
                }

            }
            lastPosition = position;
        }
        switch (bannerStyle) {
//            case BannerConfig.CIRCLE_INDICATOR:
//            case BannerConfig.CUSTOM_INDICATOR:
//                break;
            case BannerConfig.NUM_INDICATOR:
                numIndicator.setText((position + 1) + "/" + count);
                break;
            case BannerConfig.NUM_INDICATOR_TITLE:
                numIndicatorInside.setText((position + 1) + "/" + count);
                bannerTitle.setText(titles.get(position));
                break;
            case BannerConfig.CIRCLE_INDICATOR_TITLE:
            case BannerConfig.CIRCLE_INDICATOR_TITLE_INSIDE:
                bannerTitle.setText(titles.get(position));
                break;
            default:
                break;
        }

    }

    /**
     * 设置轮播图点击监听器
     * @param listener
     * @return Banner
     */
    public Banner setOnBannerClickListener(OnBannerClickListener listener) {
        this.listener = listener;
        return this;
    }

    /**
     * 设置轮播页面变化监听器
     * @param onPageChangeListener
     */
    public void setOnPageChangeListener(PageSlider.PageChangedListener onPageChangeListener) {
        mOnPageChangeListener = onPageChangeListener;
    }

    /**
     * 释放自动轮播线程任务
     */
    public void releaseBanner() {
        handler.removeCallbacksAndMessages(runner);
    }


    public Banner setViewPagerIsScroll(boolean isScroll) {
        return this;
    }

    public boolean isPrepare() {
        return isPrepare;
    }

    public boolean isStart() {
        return isStart;
    }
}
